package socket;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;

/*
 * 客户端：
 * 1.创建DataGrameSocket类
 * 2.准备数据
 * 3.打包socket类 + 服务器地址+端口号
 * 4.发送
 * 5.释放资源
 * 服务端：
 * 1.创建服务DataGrameSocket类 + 端口
 * 2.准备接受容器
 * 3.接受数据
 * 4.分析
 * 5.释放资源
 */

public class UDPTest {

	public static void main(String[] args) {
         
	}
	
	public static void test1(){
		
	}

}

class client{
	
	//希望传输double数据类型
	//将doubel类型转为byte数组(输出流)
	public static byte[] convert(double num) throws IOException{
		byte[] data = null;
		//BufferedOutputStream bos = new BufferedOutputStream()
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(bos));
		dos.writeDouble(num);
		data = bos.toByteArray();
		return data;
	}
	
	public static byte[] convert(Object o) throws IOException{
		byte[] data = null;
		//BufferedOutputStream bos = new BufferedOutputStream()
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos));
		oos.writeObject(o);
		data = bos.toByteArray();
		return data;
	}
	
	public static void init() throws IOException{
		//1.创建DataGrameSocket类
		DatagramSocket client = new DatagramSocket(6666);
		//2.准备数据
		String msg = "嗯么肯借";
		byte[] data = msg.getBytes();
		//3.打包socket类 + 服务器地址+端口号
		DatagramPacket packet = new DatagramPacket(data,data.length,new InetSocketAddress("localhost",8888));
	    //4.发送
		client.send(packet);
		//5.释放资源
		client.close();
	}
}

class server{
	
	public static Object convert1(byte[] data) throws IOException, ClassNotFoundException{
		ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
	    Object o = ois.readObject();
	    return o;
	}
	
	public static double convert(byte[] data) throws IOException{
		DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
	    double num = dis.readDouble();
	    return num;
	}
	
    public static void init() throws IOException{
    	//1.创建服务DataGrameSocket类 + 端口
		DatagramSocket dg = new DatagramSocket(8888);
		//2.准备接受容器
		byte[] container = new byte[1024];
		//将容器封装为包
		DatagramPacket dp = new DatagramPacket(container,container.length);
		//接受数据()
		dg.receive(dp);
		//4.分析
		byte[] data = dp.getData();
		int len = dp.getLength();
		System.out.println(new String(data,0,len));
		dg.close();
	}
}


